/* eslint-disable array-callback-return */
import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Col,
  Row,
  DatePicker,
  Select,
  message,
  InputNumber,
  Input,
  AutoComplete,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import Customer from '../../components/Customer'; // 客户名称
import styles from './style.less';

const { Option } = Select;
const { TextArea, Search } = Input;
const FormItem = Form.Item;
const { MonthPicker } = DatePicker;

@connect(({ oncechargecs, loading, login }) => ({
  loading: loading.models.oncechargecs,
  addEmpOnChgloading: loading.effects['oncechargecs/submitAddEmpData'], // 新增雇员一次性收费
  product: oncechargecs.product, // 产品下拉
  empNameList: oncechargecs.empNameList,
  login,
}))
@Form.create()
class AdvancedForm extends PureComponent {
  // 组件内所有数据的初始状态
  state = {
    contList: [],
    custId: null,
    idType: 1,
    empName: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    // 获取产品下拉
    dispatch({
      type: 'oncechargecs/getProductList',
      payload: {},
    });
  }

  // 客户名称
  getData = (value, options) => {
    const {
      form,
      dispatch,
      login: { baseUser, systemList },
    } = this.props;
    const { sysCode } = systemList[0];
    form.resetFields(['custContId', 'empName', 'idNo']);
    this.setState({ custId: value });
    dispatch({
      type: 'oncechargecs/updateModelData',
      payload: {
        empNameList: [],
      },
    });
    const { suppId } = options.props && options.props.fsOptions;
    if (sysCode !== 3 || (sysCode === 3 && baseUser.suppId === suppId)) {
      dispatch({
        type: 'oncechargecs/getCustcontList',
        payload: {
          custId: value,
          queryType: 3,
        },
      }).then(res => {
        if (res.success && res.data.length) {
          this.setState({ contList: res.data });
        } else {
          this.setState({ contList: [] });
        }
      });
    }
  };

  // 姓名模糊查询
  searchEmpName = value => {
    const { dispatch } = this.props;
    const { custId } = this.state;
    if (value.trim().length) {
      dispatch({
        type: 'oncechargecs/fetchEmpNameList',
        isEs: true, // 员工系统单独接口
        payload: {
          empName: value,
          custId,
        },
      });
    }
  };

  // 选择姓名
  selectEmpName = value => {
    const { empNameList, form } = this.props;
    empNameList.map(item => {
      if (item.empId === value) {
        form.setFieldsValue({ idNo: item.idCode });
        this.setState({ idType: item.idType, empName: item.empName });
      }
    });
  };

  // 输入证件号查询名字
  searchIdCode = value => {
    const { dispatch, form } = this.props;
    const { custId } = this.state;
    form.resetFields(['empName']);
    dispatch({
      type: 'oncechargecs/fetchEmpNameList',
      isEs: true, // 员工系统单独接口
      payload: {
        idNo: value,
        custId,
      },
    }).then(data => {
      if (data.length) {
        data.map(item => {
          if (item.idCode === value) {
            form.setFieldsValue({ empName: item.empId });
            this.setState({ empName: item.empName });
          }
        });
      }
    });
  };

  // 取消
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'onebilling/updateModelData',
      payload: {
        formFieldsValue: {},
        expandForm: false,
        activeKey: '1',
        data: {
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      },
    });
    router.goBack(-1);
  };

  // 表单检测 并 提交
  submitAll = () => {
    const { dispatch, form } = this.props;
    const { idType, empName } = this.state;
    let submitData = {};
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const busiYm = values.busiYm.format('YYYYMM');
        submitData = {
          pdId: values.pdName,
          custId: values.custId,
          custContId: values.custContId,
          remark: values.remark,
          empName,
          idType,
          idNo: values.idNo,
          busiYm,
          feeAmo: values.feeAmo,
        };
        if (values.feeAmo === '0') {
          message.warning('收费金额不能为 0 ');
          return;
        }
        dispatch({
          type: 'oncechargecs/submitAddEmpData',
          payload: submitData,
        }).then(res => {
          if (res.success) {
            message.success('新增成功！');
            dispatch({
              type: 'onebilling/updateModelData',
              payload: {
                formFieldsValue: {},
                expandForm: false,
                activeKey: '1',
                data: {
                  pagination: {
                    current: 1,
                    pageSize: 10,
                    total: 10,
                  },
                },
              },
            });
            router.goBack();
          } else {
            message.warning(res.message || '新增失败');
          }
        });
      }
    });
  };

  // 渲染函数
  render() {
    // 引入组件构造属性
    const { product, form, addEmpOnChgloading, empNameList = [] } = this.props;
    const { getFieldDecorator } = form;
    const { contList } = this.state;
    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Card title={<span style={{ fontWeight: 'bolder' }}>基本信息</span>}>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="产品">
                  {getFieldDecorator('pdName', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      style={{ width: '100%' }}
                      placeholder="请选择"
                      // labelInValue
                      showSearch
                      onChange={this.getpdName}
                    >
                      {product.map(item => (
                        <Option key={item.pdCode}>{item.pdName}</Option>
                      ))}
                    </HOCSelect>
                    // <Select placeholder="请选择" onChange={this.getpdName}>
                    //   {product.map(item => (
                    //     <Option key={item.pdCode}>{item.pdName}</Option>
                    //   ))}
                    // </Select>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="客户名称">
                  {getFieldDecorator('custId', {
                    rules: [{ required: false, message: '请输入' }],
                  })(<Customer getData={this.getData} isEsOnceCust />)}
                </FormItem>
              </Col>

              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="商务合同">
                  {getFieldDecorator('custContId', {
                    rules: [{ required: false, message: '请输入合同名称' }],
                  })(
                    // <Select placeholder="请选择">
                    //   {contList.map(item => (
                    //     <Option key={item.contId}>{item.contName}</Option>
                    //   ))}
                    // </Select>
                    <HOCSelect
                      style={{ width: '100%' }}
                      placeholder="请选择"
                      showSearch
                    >
                      {contList.map(item => (
                        <Option key={item.contId}>{item.contName}</Option>
                      ))}
                    </HOCSelect>
                    
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="姓名">
                  {getFieldDecorator('empName', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      placeholder="请输入关键字检索"
                      showSearch
                      showArrow={false}
                      filterOption={false}
                      onSearch={this.searchEmpName}
                      onSelect={this.selectEmpName}
                    >
                      {empNameList.length &&
                        empNameList.map(item => (
                          <Option key={item.empId} value={item.empId}>
                            {item.empName}
                          </Option>
                        ))}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="证件号">
                  {getFieldDecorator('idNo', {
                    rules: [{ required: true, message: '请输入' }],
                  })(
                    <AutoComplete>
                      <Search
                        placeholder="请输入关键字检索"
                        onSearch={value => this.searchIdCode(value)}
                      />
                    </AutoComplete>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="业务年月">
                  {getFieldDecorator('busiYm', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <MonthPicker placeholder="请选择" format="YYYY-MM" style={{ width: '100%' }} />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="收费金额">
                  {getFieldDecorator('feeAmo', {
                    rules: [
                      { required: true, message: '保留小数点后两位', pattern: /^-?\d+\.?\d{0,2}$/ },
                    ],
                  })(
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="请输入"
                      min={0}
                      max={9999999.99}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={8}>
                <FormItem label="备注">
                  {getFieldDecorator('remark', {
                    rules: [{ required: false, message: '请输入' }],
                  })(<TextArea rows={4} maxLength={200} />)}
                </FormItem>
              </Col>
            </Row>
          </Card>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={this.cancel} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button type="primary" onClick={this.submitAll} loading={addEmpOnChgloading}>
              提交
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}
export default AdvancedForm;
